package com.jnu.accounthelper.ui;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.jnu.accounthelper.R;
import com.jnu.accounthelper.db.Account;
import com.jnu.accounthelper.db.DBManager;
import com.jnu.accounthelper.db.Type;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TypeItemFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TypeItemFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ArrayList<Account> accounts=new ArrayList<>();
    private ArrayList<Type> types=new ArrayList<>();
    private RecyclerView typeRecycler;
    private ListView listView;
    private SearchView searchView;
    private TextView search;
    private TypeItemFragment.MyRecyclerViewAdapter adapter;
    private TypeAdapter typeAdapter;
    private String selectedType;
    public TypeItemFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TypeItemFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TypeItemFragment newInstance(String param1, String param2) {
        TypeItemFragment fragment = new TypeItemFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root=inflater.inflate(R.layout.fragment_type_item, container, false);

        try {
            accounts= DBManager.getAccountList();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //types.add(new Type("欠债",R.drawable.debt));
        types.add(new Type("保险",R.drawable.security));
        types.add(new Type("工资",R.drawable.salary));
        types.add(new Type("吃喝饮食", R.drawable.food));
        types.add(new Type("股票", R.drawable.stock));
        types.add(new Type("医疗",R.drawable.medicine));
        types.add(new Type("日用品",R.drawable.route));
        types.add(new Type("学习",R.drawable.study));
        types.add(new Type("水电费",R.drawable.water));
        types.add(new Type("交通",R.drawable.transporta));
        types.add(new Type("娱乐",R.drawable.entertainmen));
        types.add(new Type("其他",R.drawable.other));

        typeRecycler=root.findViewById(R.id.type_recycler);
        typeRecycler.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new TypeItemFragment.MyRecyclerViewAdapter(accounts);
        typeRecycler.setAdapter(adapter);

        listView=root.findViewById(R.id.listView);
        typeAdapter=new TypeAdapter(getContext(),R.layout.type_item,types);
        listView.setAdapter(typeAdapter);

        searchView=root.findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                accounts=DBManager.selectByRemark(selectedType,query);
                adapter.notifyDataSetChanged();
               Log.d("搜索",query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                accounts=DBManager.selectByRemark(selectedType,newText);
                adapter.notifyDataSetChanged();
                Log.d("改变",newText);
                return false;
            }
        });

        return root;
    }

    public class TypeAdapter extends ArrayAdapter<Type> {
        private int resourceId;
        public TypeAdapter(Context context, int resource, List<Type> data){
            super(context,resource,data);
            resourceId=resource;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            final Type item=getItem(position);
            View view;
            ViewHolder holder=new ViewHolder();  // viewHolder 是提升 ListView 运行效率
            if(convertView==null){
                view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
                holder.tv=view.findViewById(R.id.type_item_text);
                holder.iv=view.findViewById(R.id.type_item_image);
                view.setTag(holder);
            } else {
                view = convertView;
                holder=(ViewHolder) view.getTag();
            }
            holder.tv.setText(item.getName());
            holder.iv.setImageResource(item.getCoverResourceId());
            holder.iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("item",item.getName());
                    try {
                        accounts=DBManager.getAccountsByType(item.getName());
                        selectedType=item.getName();
                        adapter.notifyDataSetChanged();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(getContext(),"you clicked button"+item.getName(), Toast.LENGTH_SHORT).show();
                }
            });
            return view;
        }
        class ViewHolder{
            TextView tv;
            ImageView iv;
        }
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter{
        //private List<Account> accounts;


        public MyRecyclerViewAdapter(List<Account> accounts) {
            //this.accounts=accounts;
        }
        @NonNull
        //加载视图
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.account_item_holder, parent, false);
            return new TypeItemFragment.MyRecyclerViewAdapter.MyViewHolder(view);


        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            TypeItemFragment.MyRecyclerViewAdapter.MyViewHolder holder =(TypeItemFragment.MyRecyclerViewAdapter.MyViewHolder)Holder;
            holder.getImageView().setImageResource(accounts.get(position).getCoverResourceId());
            holder.getType().setText(accounts.get(position).getType());
            holder.getNumber().setText(accounts.get(position).getNumber()+"");
            holder.getRemark().setText(accounts.get(position).getRemark());
            holder.getDate().setText(accounts.get(position).getDate());
        }



        @Override
        public int getItemCount() {
            return accounts.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder{

            private final ImageView imageView;
            private final TextView type;
            private final TextView remark;
            private final TextView number;
            private final TextView date;

            public MyViewHolder(View view) {
                super(view);

                this.imageView=view.findViewById(R.id.image_view_book_cover);
                this.type=view.findViewById(R.id.type);
                this.remark=view.findViewById(R.id.remark);
                this.number=view.findViewById(R.id.number);
                this.date=view.findViewById(R.id.item_date);

            }

            public TextView getDate() {
                return date;
            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getType() {
                return type;
            }

            public TextView getRemark() {
                return remark;
            }

            public TextView getNumber() {
                return number;
            }





        }
    }
}